﻿using System;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Windows.Forms;
using APPLICATION.Properties;
using DAL;
using APPLICATION.UserManager;

namespace APPLICATION
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void toolStripStatusLabel1_Click(object sender, EventArgs e)
        {
            SettingsConfig configWindow = new SettingsConfig();
            configWindow.ShowDialog();
        }

        private void Login_Load(object sender, EventArgs e)
        {
            toolStripStatusDBName.Text = "Server Adress: " + APPLICATION.Properties.Settings.Default.ServerAdress;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void configurationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SettingsConfig configWindow = new SettingsConfig();
            configWindow.ShowDialog();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            GetConnectionString connString = new GetConnectionString();
            SettingsConfig configWindow = new SettingsConfig();


            using (SqlConnection connection = new SqlConnection(connString.connStringFromLogin(txtUserName.Text, txtPassword.Text)))
            {

                String strUsername, strPassword;

                strUsername = txtUserName.Text.Trim();
                strPassword = txtPassword.Text.Trim();

                //Если ЛОГИН и ПАРОЛЬ пустые тогда выдаст ошибку о заполнении обеих полей
                if (strUsername == "" | strPassword == "")
                {
                    //Текст ошибки
                    MessageBox.Show("Поля логин и пароль не могут быть пустыми", "TIMS");
                    //Проверит какое поле пустое и соответственно фокусирет на это поле
                    if (strUsername == "") { txtUserName.Focus(); }
                    else { txtPassword.Focus(); }
                }
                else
                {

                    try
                    {
                        // Try to Open connection
                        connection.Open();

                        // Applay ConnectionString value  to  static  class 
                        globals.APPCONNSTRING = connString.connStringFromLogin(strUsername, strPassword);

                        // Applay  ConnectionString value to Settings but  do not  save  it !
                        //Settings.Default.TIMSConnectionString1 = globals.APPCONNSTRING;

                        // Return Dialog result OK
                        DialogResult = DialogResult.OK;

                        //Close COnnection
                        connection.Close();

                        Close();

                    }
                    catch (SqlException ex)
                    {

                        SqlExeptionMessageClass expetionMesageStrings = new SqlExeptionMessageClass();
                        DisplayErrors(expetionMesageStrings.TranslateException(ex));

                    }

                }

            }

        }


        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string strUsername = txtUserName.Text.Trim();
            string strPassword = txtPassword.Text.Trim();
            do_login(strUsername, strPassword);
        }
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btnLogin.Enabled = true;
        }

        private void txtUsername_Enter(object sender, EventArgs e) { txtUserName.SelectAll(); }

        private void txtPassword_Enter(object sender, EventArgs e) { txtPassword.SelectAll(); }

        private void do_login(string strUsername, string strPassword)
        {
            /*
            //Здесь Создается строка подключения
            string strConString;
            GetConnectionString connString = new GetConnectionString();
            strConString =   connString.connString();
            //strConString = "Data Source=" + strServer + ";Initial Catalog=test;Persist Security Info=True;User ID=test;Password=test";
            
            //Здесь создается компоненты  для подключения к базе
            SqlConnection cn = new SqlConnection();
            SqlCommand cmd = new SqlCommand();
            SqlDataReader dr;


            try
            {
                cn.ConnectionString = strConString;
                cn.Open();  //Открываем соединение
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "sp_login";   //Задаем имя хранимой процедуры
                cmd.Parameters.Add("@username", SqlDbType.Char, 25).Value = strUsername;
                cmd.Parameters.Add("@password", SqlDbType.Char, 25).Value = strPassword;
                cmd.Connection = cn;
                dr = cmd.ExecuteReader();
                if (dr.HasRows)
                {
                    //Пользователь существует, остальной код нужно прописать здесь...
                    dr.Read();
                    MessageBox.Show("Welcome " + dr.GetValue(2).ToString() + "\n Your ID: " + dr.GetValue(3).ToString() + "\n Your role id: " + dr.GetValue(4).ToString(), "TIMS");
                }
                else
                {
                    //Пользователь не существует, выдадим ошибку!
                    MessageBox.Show("Неправильный логин и/или пароль", "TIMS");
                  
                }
                cn.Close();
            }
            catch (Exception ex)
            {
                if (cn.State != ConnectionState.Open) { MessageBox.Show("Невозможно соединиться с сервером: " + cn.DataSource); }
                else
                {
                    MessageBox.Show("Произошла внутренная ошибка", "TIMS");
                }
                //string strPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
               
            }
             * */

        }

        private void backgroundWorker1_DoWork_1(object sender, DoWorkEventArgs e)
        {
            string strUsername = txtUserName.Text.Trim();
            string strPassword = txtPassword.Text.Trim();
            do_login(strUsername, strPassword);
        }

        private void backgroundWorker1_RunWorkerCompleted_1(object sender, RunWorkerCompletedEventArgs e)
        {
            btnLogin.Enabled = true;
        }

        #region Interface tools
        /// <summary>
        /// Displays Formatted exceptions
        /// </summary>
        private void DisplayErrors(string ErrorString)
        {
            DialogResult result = MessageBox.Show(ErrorString, "Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error);
            if (result == DialogResult.Abort)
            {
                Application.Exit();
            }

            Cursor = Cursors.Default;
        }

        #endregion

        private void txtUserName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
               // txtPassword.Focus();
            }
        }

        private void txtPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
               // btnLogin.Focus();
            }

        }
    }
}
